package concurrent.lock;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program JavaBase
 * @description: 单应用锁
 * @author: zhanglu
 * @create: 2022-09-29 14:30:00
 */
@Slf4j
public class StandaloneLockHelper {

    private static ConcurrentHashMap<Integer, ReentrantLock> userLockMap = new ConcurrentHashMap<>();

    @Test
    public void bussiness() throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> bussinessMethod(1)).start();
            Thread.sleep(500);
        }
        Thread.sleep(500);
        for (int i = 0; i < 20; i++) {
            new Thread(() -> bussinessMethod(2)).start();
        }
        Thread.sleep(500);
        for (int i = 0; i < 20; i++) {
            new Thread(() -> bussinessMethod(3)).start();
        }
        Thread.sleep(500);
        for (int i = 0; i < 20; i++) {
            new Thread(() -> bussinessMethod(1)).start();
        }
        Thread.sleep(500);
        for (int i = 0; i < 20; i++) {
            new Thread(() -> bussinessMethod(2)).start();
        }
        Thread.sleep(500);
        for (int i = 0; i < 20; i++) {
            new Thread(() -> bussinessMethod(3)).start();
        }
        Thread.currentThread().join();
    }

    public void bussinessMethod(Integer userId){
        boolean tryLock = this.lock(userId);
        if(!tryLock){
            return;
        }
        try {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally {
            this.unlock(userId);
        }
    }

    public ReentrantLock getUserLock(Integer id){
        userLockMap.putIfAbsent(id, new ReentrantLock());
        return userLockMap.get(id);
    }

    public boolean lock(Integer id){
        ReentrantLock userLock = getUserLock(id);
        try {
            boolean rs = userLock.tryLock(2, TimeUnit.SECONDS);  //2s锁过期
            if(rs){
                userLockMap.put(id, userLock);
                log.info("lock:" + id);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("lock exception：" + e.getMessage());
        }
        return false;
    }

    public void unlock(Integer id){
        log.info("unlock:" + id);
        try {
            userLockMap.get(id).unlock();
            userLockMap.remove(id);
        } catch (Exception e) {
            log.error("unlock exception：" + e.getMessage());
        }
    }


}
